package com.git.controller;

import java.util.Date;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.data.redis.serializer.SerializationException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.git.domain.BaseResponse;
import com.git.domain.ResultCode;
import com.git.mapper.DemoRedisDao;

@Controller
public class DemoController {
	private static final String userIdPre = "userid_";
	private static final long limit = 1*60*1000;
	private static final long liveTime = 1*60;
	/**
	 * 一小时，最多能登录5次
	 * @param userId
	 * @return
	 * @throws Exception 
	 * @throws SerializationException 
	 */
	@RequestMapping("login")
	@ResponseBody
	public BaseResponse login(String userId) throws SerializationException, Exception{
		if (StringUtils.isBlank(userId)) {
			return BaseResponse.FAIL();
		}
		String key = userIdPre+userId;
		Long listCount = DemoRedisDao.getListCount(key.getBytes());
		if (listCount<5) {
			DemoRedisDao.putListObject(key, new Date().getTime(), liveTime);
			
			return BaseResponse.SUCCESSFUL();
		}else{
			//这里判断最早的记录距离现在是不是超过了1h
			long first = (long) DemoRedisDao.getListObjectByIndex(key, 0);
			if (new Date().getTime()-first > limit) {
				//说明记录中最早的已经超过了1h，允许登录
				DemoRedisDao.removeListFirst(key.getBytes());
				DemoRedisDao.putListObject(key, new Date().getTime(), liveTime);
				return BaseResponse.SUCCESSFUL();
			}else{
				return new BaseResponse(ResultCode.FAIL_CODE, "登录超过5次被拒绝");
			}
		}
		
		//记录一条登录信息
	}
	public static void main(String[] args) {
		Date date = new Date(1490862340933l);
		System.out.println(DateFormatUtils.format(date, "yyyyMMdd-HHmmss"));
	}
}
